import * as d3 from "d3";
import cloud from "d3-cloud";

export class WordCloud {
    constructor(container) {
        this.container = container;
        this.margin = { top: 40, right: 20, bottom: 20, left: 20 };
        this.width = 400;
        this.height = 300;
        
        // 添加专业选择器
        this.selector = d3.select(container)
            .append('select')
            .style('margin-bottom', '15px')
            .style('padding', '8px 12px')  
            .style('width', '180px')      
            .style('border', '1px solid #dcdfe6')  
            .style('border-radius', '4px')        
            .style('background-color', '#fff')     
            .style('color', '#606266')            
            .style('font-size', '14px')           
            .style('cursor', 'pointer')           
            .style('transition', 'all 0.3s')      
            .on('mouseover', function() {
                d3.select(this)
                    .style('border-color', '#c0c4cc');  
            })
            .on('mouseout', function() {
                d3.select(this)
                    .style('border-color', '#dcdfe6');  
            })
            .on('change', (event) => this.onMajorChange(event));
        this.selector
            .style('-webkit-appearance', 'none')  
            .style('-moz-appearance', 'none')
            .style('appearance', 'none')
            .style('background-image', 'url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 24 24\' fill=\'none\' stroke=\'%23606266\' stroke-width=\'2\' stroke-linecap=\'round\' stroke-linejoin=\'round\'%3e%3cpolyline points=\'6 9 12 15 18 9\'%3e%3c/polyline%3e%3c/svg%3e")')
            .style('background-repeat', 'no-repeat')
            .style('background-position', 'right 8px center')
            .style('background-size', '12px')
            .style('padding-right', '30px');  

        // 创建SVG容器
        this.svg = d3.select(container)
            .append('svg')
            .attr('width', this.width + this.margin.left + this.margin.right)
            .attr('height', this.height + this.margin.top + this.margin.bottom)
            .append('g')
            .attr('transform', `translate(${this.width/2 + this.margin.left},${this.height/2 + this.margin.top})`);

        // 添加标题
        this.title = this.svg.append('text')
            .attr('x', 0)
            .attr('y', -this.height/2 - 20)
            .attr('text-anchor', 'middle')
            .style('font-size', '20px')
            .style('font-weight', 'bold')
            .text('AI工具使用场景词云');

        this.categoryColors = {
            // 学习相关
            '编程': '#4e79a7',
            '数学': '#4e79a7',
            '作业': '#76b7b2',
            
            // 写作相关
            '写作': '#59a14f',
            '报告': '#59a14f',
            '论文': '#59a14f',
            
            // 辅助工具
            'PPT': '#f28e2c',
            '翻译': '#f28e2c',
            '改写': '#f28e2c',
            
            // 思考分析
            '分析': '#af7aa1',
            '思路': '#af7aa1',
            '提炼': '#af7aa1',
            
            // 问答查找
            '问答': '#e15759',
            '查找': '#e15759',
            
            // 其他
            '图像': '#9c755f',
            '生活': '#bab0ab'
        };

        this.handlers = {};  
    }
    
    update(data) {
        this.data = data;
        this.svg.selectAll('*:not(text)').remove();
        
        // 更新专业选择器
        this.selector
            .selectAll('option')
            .data(['所有专业', ...new Set(data.map(d => d.major))])
            .join('option')
            .text(d => d);
            
        // 初始渲染词云
        this.data = data;
        this.renderWordCloud('所有专业');
    }
    
    on(eventName, handler) {
        this.handlers[eventName] = handler;
    }
    
    onMajorChange(event) {
        const major = event.target.value;
        if (major !== '所有专业') {
            this.handlers['majorHover']?.(major);
        } else {
            this.handlers['majorOut']?.();
        }
        this.renderWordCloud(major);
    }
    
    renderWordCloud(selectedMajor) {
        // 过滤数据
        const filteredData = selectedMajor === '所有专业' 
            ? this.data 
            : this.data.filter(d => d.major === selectedMajor);

        // 统计分类频次
        let categoryCounts = {};
        filteredData.forEach(item => {
            categoryCounts[item.category] = (categoryCounts[item.category] || 0) + 1;
        });

        // 转换为词云数据格式并排序
        const words = Object.entries(categoryCounts)
            .map(([text, value]) => ({ text, value }))
            .sort((a, b) => b.value - a.value); 

        // 词云布局配置
        const layout = cloud()
            .size([this.width * 0.75, this.height * 0.75])
            .words(words)
            .padding(2)
            .rotate(() => 0)
            .random(() => 0.5)
            .spiral('archimedean')
            .font("Arial")
            .fontSize(d => {
                const sizeScale = d3.scalePow()
                    .exponent(1.3)
                    .domain([1, Math.max(...words.map(w => w.value))])
                    .range([20, 70]);
                return sizeScale(d.value);
            })
            .on("end", words => {
                // 根据词频排序，确保高频词在上层
                words.sort((a, b) => b.value - a.value);
                
                const cloud = this.svg.selectAll(".word")
                    .data(words)
                    .join("text")
                    .attr("class", "word")
                    .style("font-size", d => `${d.size}px`)
                    .style("font-family", "Arial")
                    .style("font-weight", "bold")
                    .style("fill", d => this.categoryColors[d.text])
                    .attr("text-anchor", "middle")
                    .attr("transform", d => `translate(${d.x},${d.y - 40})`)
                    .style("cursor", "pointer")
                    .text(d => d.text);

                // 添加交互效果
                cloud
                    .on("mouseover", function(event, d) {
                        d3.select(this)
                            .transition()
                            .duration(200)
                            .style("opacity", 0.7)
                            .style("font-size", `${d.size * 1.2}px`)
                            .style("z-index", 1000);  
                    })
                    .on("mouseout", function(event, d) {
                        d3.select(this)
                            .transition()
                            .duration(200)
                            .style("opacity", 1)
                            .style("font-size", `${d.size}px`)
                            .style("z-index", 1);
                    });

                cloud.append("title")
                    .text(d => `${d.text}: ${d.value}次`);
            });

        layout.start();
    }
} 